<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <title>客户管理页面</title>
    <link rel="stylesheet" th:href="@{/layui/css/layui.css}">
    <script th:src="@{/layui/layui.js}"></script>
</head>
<body>
<script type="text/html" id="barDemo">

    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn  layui-btn-normal layui-btn-xs" lay-event="resetPassword">业务登记</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">回访</a>
</script>
<form class="layui-form" action="" id="save_user_form" style="display: none">
    <div class="layui-form-item">
        <label class="layui-form-label">登录名</label>
        <div class="layui-input-block">
            <input type="text" name="loginName" id="loginName" required lay-verify="required" placeholder="请输入登录名称"
                   autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">密 码</label>
        <div class="layui-input-block">
            <input type="text" name="password" required lay-verify="required" placeholder="请设置密码" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">真实姓名</label>
        <div class="layui-input-inline">
            <input type="text" name="userName" required lay-verify="required" placeholder="请输入真实姓名" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">邮箱</label>
        <div class="layui-input-inline">
            <input type="text" name="email" required lay-verify="email" placeholder="请输入电子邮箱" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">手机号</label>
        <div class="layui-input-inline">
            <input type="text" name="phonenumber" required lay-verify="required|phone" placeholder="请输入手机号"
                   autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">部门</label>
        <div class="layui-input-block">
            <select name="deptId" lay-verify="required" lay-search="">
                <option th:each="dept:${deptList}" th:value="${dept.deptId}" th:text="${dept.deptName}"></option>
            </select>
        </div>
    </div>

    <div class="layui-form-item">
        <div class="layui-inline">
            <label class="layui-form-label">状态</label>
            <div class="layui-input-block">
                <input type="checkbox" name="status" lay-skin="switch" lay-text="正常|禁用" checked value="0">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">性别</label>
            <div class="layui-input-block">
                <input type="radio" name="sex" value="0" title="男" checked="">
                <input type="radio" name="sex" value="1" title="女">
            </div>
        </div>
    </div>
    <div class="layui-form-item" pane="">
        <label class="layui-form-label">角色</label>
        <div class="layui-input-block">
            <input th:each="role:${roleList}" name="role" type="checkbox" th:value="${role.roleId}"
                   lay-skin="primary"
                   th:text="${role.roleName}">
        </div>
        <input hidden="hidden" name="salt">
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">备注</label>
        <div class="layui-input-inline">
            <input type="text" name="remark" required lay-verify="required" placeholder="请输入备注信息" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>
<!--===========================================更新用户信息==============================================================-->
<form class="layui-form" action="" id="update_user_form" style="display: none" lay-filter="update_user_form">
    <!--隐藏输入框，保存主键-->
    <input type="hidden" name="userId">
    <input type="hidden" name="loginName">
    <input type="hidden" name="password">
    <div class="layui-form-item">
        <label class="layui-form-label">真实姓名</label>
        <div class="layui-input-inline">
            <input type="text" name="userName" required lay-verify="required" placeholder="请输入真实姓名" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">邮箱</label>
        <div class="layui-input-inline">
            <input type="text" name="email" required lay-verify="email" placeholder="请输入电子邮箱" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">手机号</label>
        <div class="layui-input-inline">
            <input type="text" name="phonenumber" required lay-verify="required|phone" placeholder="请输入手机号"
                   autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">部门</label>
        <div class="layui-input-block">
            <select name="deptId" lay-verify="required" lay-search="">
                <option th:each="dept:${deptList}" th:value="${dept.deptId}" th:text="${dept.deptName}"></option>
            </select>
        </div>
    </div>

    <div class="layui-form-item">
        <div class="layui-inline">
            <label class="layui-form-label">状态</label>
            <div class="layui-input-block">
                <input type="checkbox" name="status" lay-skin="switch" lay-text="正常|禁用" checked value="0">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">性别</label>
            <div class="layui-input-block">
                <input type="radio" name="sex" value="0" title="男" checked="">
                <input type="radio" name="sex" value="1" title="女">
            </div>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">角色</label>
        <div class="layui-input-block">
            <input class="role_check" th:each="role:${roleList}" th:name="${role.roleKey}" type="checkbox"
                   th:value="${role.roleId}"
                   lay-skin="primary" th:text="${role.roleName}">
        </div>
        <input hidden="hidden" name="salt">
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">备注</label>
        <div class="layui-input-inline">
            <input type="text" name="remark" required lay-verify="required" placeholder="请输入备注信息" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="formUpdateUser">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>
<!--=========================================重置密码===============================-->
<form class="layui-form" action="" id="reset_password_form" style="display: none" lay-filter="reset_password_form">
    <!--隐藏输入框，保存主键-->
    <input type="hidden" name="userId">
    <div class="layui-form-item">
        <label class="layui-form-label">密码</label>
        <div class="layui-input-inline">
            <input type="text" name="password" required lay-verify="required" placeholder="请输入新密码" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="formResetPassword-flter">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>
<div class="layui-fluid">
    <!--=============================条件查询==================================-->
    <div class="layui-card" style="padding-top: 30px">
        <form class="layui-form">
            <div class="layui-inline">
                <label class="layui-form-label">手机号：</label>
                <div class="layui-input-inline">
                    <input type="text" class="layui-input" id="searchPhonenumber" name="searchPhonenumber"
                           placeholder="修改人"
                           width="80px">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">联系人：</label>
                <div class="layui-input-inline">
                    <input type="text" class="layui-input" id="searchLoginName" name="searchLoginName" placeholder="登录名"
                           width="80px">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">申请人：</label>
                <div class="layui-input-inline">
                    <input type="text" class="layui-input" id="searchUserName" name="searchUserName"
                           placeholder="创建人"
                           width="80px">
                </div>
            </div>

            <div class="layui-inline">
                <button class="layui-btn" lay-submit="search_submits" lay-filter="search_filter">查询</button>
                <button id="search_reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </form>
    </div>
    <div class="layui-card">
        <table id="demo" lay-filter="userTable"></table>
    </div>
</div>
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="addUser">添加</button>
        <button class="layui-btn layui-btn-danger layui-btn-sm" lay-event="deleteBatch">删除</button>
    </div>
</script>
</body>
<script>
    layui.use(['layer', 'form', 'table', 'jquery'], function () {
        var table = layui.table;
        var form = layui.form;
        var $ = layui.jquery;

        //第一个实例
        var myTable = table.render({
            elem: '#demo'
            , id: 'tableReload'//重载数据表格
            , height: 'full-100'
            , url: '/custom/selectAllCustom' //数据接口
            , page: true //开启分页
            , limit: 5//默认一页显示5条数据
            , limits: [5, 10, 15, 20, 50, 100]//默认一页显示5条数据
            , toolbar: '#toolbarDemo'//此处的id是html代码段
            , cols: [
                [ //表头
                    {field: 'customId', title: '客户编号', width: 80, fixed: 'left', checkbox: true},
                    {field: 'customId', title: '客户编号', width: 100, sort: true}
                    , {field: 'contact', title: '联系人姓名', width: 120, sort: true}
                    , {field: 'phone', title: '手机号', width: 120}
                    , {field: 'applicant', title: '申请人', width: 120}
                    , {field: 'customAddress', title: '地址', width: 120}
                    , {
                    field: 'userName', title: '代理人', width: 100,
                    templet: function (d) {
                        return d.user.userName
                    }
                }
                    , {field: 'createBy', title: '创建人', width: 80}
                    , {field: 'createTime', title: '创建时间', width: 160}
                    , {field: 'updateBy', title: '修改人', width: 80}
                    , {field: 'updateTime', title: '修改时间', width: 135}
                    , {field: 'remark', title: '备注', width: 135}
                    , {field: 'proxyId', title: '代理人Id', width: 100}
                    , {title: '操作', width: 235, toolbar: '#barDemo', fixed: 'right'}
                ]]
        });
        //监听头工具栏事件
        table.on('toolbar(userTable)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id)
                , data = checkStatus.data; //获取选中的数据
            switch (obj.event) {
                case 'addUser':
                    layer.open({
                        title: '添加员工',
                        type: 1,
                        content: $('#save_user_form'),
                        area: ['500px', '480px']
                    });
                    break;
                case 'update':
                    if (data.length === 0) {
                        layer.msg('请选择一行');
                    } else if (data.length > 1) {
                        layer.msg('只能同时编辑一个');
                    } else {
                        layer.alert('编辑 [id]：' + checkStatus.data[0].id);
                    }
                    break;
                case 'deleteBatch':
                    if (data.length === 0) {
                        layer.msg('请选择一行');
                    } else {
                        //对于删除或者是其他敏感操作，一定要让用户确认。
                        layer.confirm('确定要删除吗？', function () {
                            //请求后台批量删除接口
                            $.ajax({
                                url: '/user/deleteBatchUser',
                                dataType: 'json',
                                contentType: "application/json;charset=UTF-8",
                                type: 'POST',
                                data: JSON.stringify(data),//将js对象转成json串传入到后台
                                success: function (result) {
                                    layer.closeAll();//关闭对话框
                                    layer.msg(result.msg);
                                    myTable.reload();//重新加载表格数据
                                }
                            })

                        })

                    }
                    break;
            }
            ;
        });

        //监听保存用户表单的提交
        form.on('submit(formDemo)', function (data) {
            data.field.status = data.field.status ? 0 : 1;
            var checkeds = selectCheckeds("role");
            //盐值在添加的时候没有用处，所以将角色信息放入到盐值中传入后端
            data.field.salt = checkeds;
            console.log(checkeds);
            $.ajax({
                url: '/user/saveUser',
                dataType: 'json',
                type: 'POST',
                data: data.field,
                success: function (result) {
                    layer.closeAll();//关闭对话框
                    layer.msg(result.msg);
                    myTable.reload();//重新加载表格数据
                }
            })
            return false;
        });
        //监听修改用户表单的提交
        form.on('submit(formUpdateUser)', function (data) {
            data.field.status = data.field.status ? 0 : 1;
            var checkeds = selectCheckeds();
            //盐值在添加的时候没有用处，所以将角色信息放入到盐值中传入后端
            data.field.salt = checkeds;
            $.ajax({
                url: '/user/updateUser',
                dataType: 'json',
                type: 'POST',
                data: data.field,
                success: function (result) {
                    layer.closeAll();//关闭对话框
                    layer.msg(result.msg);
                    myTable.reload();//重新加载表格数据
                }
            })
            return false;
        });
        //登录名校验
        $("#loginName").blur(function () {
            var node = this;
            console.log(node)
            $.ajax({
                type: "POST",
                url: "/user/checkUserName",
                async: false, //改为同步请求
                data: {username: node.value},
                dataType: 'json',
                success: function (data) {
                    if (data.code == 0) {
                    } else {
                        node.focus();
                        layer.msg(data.msg, {icon: 5});
                    }
                }
            });
        });

        // 获取选中复选框项
        function selectCheckeds(name) {
            var checkeds = "";
            // 保存用户
            if (name != null) {
                $('input:checkbox[name="' + name + '"]:checked').each(function (i) {
                    if (0 == i) {
                        checkeds = $(this).val();
                    } else {
                        checkeds += ("," + $(this).val());
                    }
                });
                //修改用户
            } else {
                $('.role_check:checked').each(function (i) {
                    if (0 == i) {
                        checkeds = $(this).val();
                    } else {
                        checkeds += ("," + $(this).val());
                    }
                });
            }

            return checkeds;
        }

        //监听查询表单的提交事件
        form.on('submit(search_filter)', function (data) {
            var formData = data.field;
            //数据表格重载
            table.reload('tableReload', {
                page: {
                    curr: 1 //重新从第 1 页开始
                }
                , where: {//这里传参  向后台
                    searchLoginName: formData.searchLoginName,
                    searchUserName: formData.searchUserName,
                    searchPhonenumber: formData.searchPhonenumber
                }
            });
            return false;//false：阻止表单跳转  true：表单跳转
        });
        //监听重置密码表单的提交事件
        form.on('submit(formResetPassword-flter)', function (data) {
            $.ajax({
                url: '/user/resetPassword',
                dataType: 'json',
                type: 'POST',
                data: data.field,
                success: function (result) {
                    layer.closeAll();//关闭对话框
                    layer.msg(result.msg);
                }
            })
            return false;
        });
        //监听行工具事件
        table.on('tool(userTable)', function (obj) { //注：tool 是工具条事件名，userTable 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值
            if (layEvent === 'detail') {
                layer.msg('查看操作');
            } else if (layEvent === 'delete') {
                layer.confirm('真的删除行么', function (index) {
                    /*  obj.del(); //删除对应行（tr）的DOM结构
                      layer.close(index);*/
                    //向服务端发送删除指令
                    console.log(data);
                    $.ajax({
                        url: '/user/deleteUser',
                        dataType: 'json',
                        type: 'POST',
                        data: {userId: data.userId},
                        success: function (result) {
                            layer.closeAll();//关闭对话框
                            layer.msg(result.msg);
                            myTable.reload();//重新加载表格数据
                        }
                    })
                });
            } else if (layEvent === 'resetPassword') {
                form.val('reset_password_form', {
                    "userId": data.userId
                });
                layer.open({
                    title: '重置密码',
                    type: 1,
                    content: $('#reset_password_form'),
                    area: ['400px', '150px']
                });
            } else if (layEvent === 'edit') {

                //将修改前的数据赋值给修改表单
                form.val('update_user_form', {
                    "userId": data.userId
                    , "loginName": data.loginName // "name": "value"
                    , "password": data.orderNum
                    , "userName": data.userName
                    , "email": data.email
                    , "phonenumber": data.phonenumber
                    , "deptId": data.deptId
                    , "status": data.status == 0 ? true : false //开关状态
                    , "sex": data.sex
                    , "remark": data.remark

                });
                //设置checkbox回显
                $.ajax({
                    url: '/user/getRoleCheckByUserId',
                    dataType: 'json',
                    type: 'POST',
                    data: {userId: data.userId},
                    success: function (result) {
                        console.log(result.data)
                        form.val('update_user_form', result.data);
                    }
                });
                layer.open({
                    title: '编辑用户',
                    type: 1,
                    content: $('#update_user_form'),
                    area: ['500px', '480px']
                });
            }
        });
        //点击重置按钮，清除查询关键字，并且重新加载表格数据
        $("#search_reset").on("click", function () {
            $("#searchLoginName").val = null;
            $("#searchUserName").val = null;
            $("#searchPhonenumber").val = null;
            myTable.reload();//重新加载表格数据
        })
    });
</script>
</html>